package DataBase;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;



public class AdministratorManager {
	public static DbcpBean dbcp ;
	static{
		dbcp = new DbcpBean();
	}
	public static int insert(Administrator admin) {
//		DbcpBean dbcp = new DbcpBean();
		Connection conn = dbcp.getConnection();
		int result = 0;
		if(conn != null){
			try {
				Statement stmt = conn.createStatement();
				String sql = "insert into tb_administrator (admin_account,admin_pwd) values ('"
					+ admin.getAdmin_account() + "' , '" 
					+ admin.getAdmin_pwd() + "');";
				result  = stmt.executeUpdate(sql);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				try {
					conn.close();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				e.printStackTrace();
			}			
		}
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return result;
	}

	public static ArrayList<Administrator> select(String admin_account) {
		// TODO Auto-generated method stub
//		DbcpBean dbcp = new DbcpBean();
		Connection conn = dbcp.getConnection();
		ResultSet result = null;
		ArrayList<Administrator> admins = new ArrayList<Administrator>();
		if(conn != null){
			try {
				Statement stmt = conn.createStatement();
				String sql = null;
				if(admin_account == ""){
					sql = "select * from tb_Administrator";
					
				}
				else{
					sql = "select * from tb_Administrator where admin_account = '"
						+ admin_account +"';";
				}
				result  = stmt.executeQuery(sql);
				while(result.next()){
					Administrator admin = new Administrator();
					admin.setAdmin_ID(result.getInt("admin_ID"));
					admin.setAdmin_account(result.getString("admin_account"));
					admin.setAdmin_pwd(result.getString("admin_pwd"));
					admins.add(admin);
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				try {
					conn.close();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				e.printStackTrace();
			}			
		}
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return admins;
	}
    

	
	
	

	public static void main(String[] args) {   
		Administrator admin = new Administrator();
		admin.setAdmin_account("admin");
		admin.setAdmin_pwd("admin");
		if(AdministratorManager.insert(admin) == 0){
			System.out.println("插入失败");
		}
		System.out.println(AdministratorManager.select("admin"));
	}

}
